package com.southminority.ethnic.controller.admin.excel;

import com.southminority.ethnic.common.exception.BusinessException;
import com.southminority.ethnic.common.result.R;
import com.southminority.ethnic.pojo.MinorityLanguageSpeech;
import com.southminority.ethnic.pojo.User;
import com.southminority.ethnic.service.language.MinorityLanguageSpeechService;
import com.southminority.ethnic.service.user.UserService;
import com.southminority.ethnic.until.ExcelUntil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import java.util.List;

@Slf4j
@Tag(name = "excle-语言数据库-词汇", description = "Excle导入导出")
@RestController
@RequestMapping("/admin/language-speech-excel")
@CrossOrigin
public class LanguageSpeechExcelController {
    @Autowired
    private MinorityLanguageSpeechService service;

    //导出所有用户信息
    @GetMapping("/output")
    @Operation(summary = "Excel导出全部数据", description = "Excel导出全部数据")
    public ResponseEntity<byte[]> outputExcel() {
        try {
            List<MinorityLanguageSpeech> dataList=service.list();
            byte[] excelBytes = ExcelUntil.exportExcel(dataList);

            String fileName = "output_excel";
            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 处理中文文件名
            String encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
            headers.setContentDispositionFormData("attachment", encodedFileName);

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    //获取导入模版
    @GetMapping("/mb-input")
    @Operation(summary = "获取导入模版", description = "获取导入模版")
    public ResponseEntity<byte[]> mbInputExcel() {
        try {

            String fileName = "input_excel";

            byte[] excelBytes = ExcelUntil.mbExcel(MinorityLanguageSpeech.class);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            // 处理中文文件名
            String encodedFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
            headers.setContentDispositionFormData("attachment", encodedFileName);

            return new ResponseEntity<>(excelBytes, headers, HttpStatus.OK);
        } catch (DuplicateKeyException e) {
            // 捕获唯一约束冲突异常，进行处理
            // 1. 记录日志（方便排查具体重复的键）
            log.error("插入数据时发生唯一约束冲突", e);

            // 2. 提取异常信息中的重复键（可选，更友好的提示）
            String errorMsg = e.getMessage();

            // 3. 抛出自定义异常（让Controller层捕获并返回给前端）
            throw new BusinessException("数据重复已存在，请检查后重试\n错误信息：" + errorMsg);
        }catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    //导入用户信息
    @PostMapping("/input")
    @Operation(summary = "Excel批量导入数据", description = "Excel批量导入数据")

    public R<String> importAndSave(@RequestParam("file") MultipartFile file) {
        try {
            // 1. 解析Excel为实体类集合（以User为例，根据实际实体类修改）
            List<MinorityLanguageSpeech> userList = ExcelUntil.importExcel(file, MinorityLanguageSpeech.class);

            // 2. 保存到数据库（通过服务层）
            //userService.saveAll(userList);

            return R.result(service.InputList(userList), "导入成功，共" + userList.size() + "条数据");
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("导入失败：" + e.getMessage());
        }
    }
}
